/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.guobo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.guobo.dao.RegionDao;
import com.thinkgem.jeesite.modules.guobo.dao.RegionUserDao;
import com.thinkgem.jeesite.modules.guobo.entity.Region;
import com.thinkgem.jeesite.modules.guobo.entity.RegionUser;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;

/**
 * 区域Service
 * @author wudavid
 * @version 2017-03-31
 */
@Service
@Transactional(readOnly = true)
public class RegionService extends CrudService<RegionDao, Region> {

	@Autowired
	UserDao userDao;
	
	@Autowired
	RegionUserDao regionUserDao;
	
	public Region get(String id) {
		return super.get(id);
	}
	
	public List<Region> findList(Region region) {
		return super.findList(region);
	}
	
	public Page<Region> findPage(Page<Region> page, Region region) {
		return super.findPage(page, region);
	}
	
	@Transactional(readOnly = false)
	public void save(Region region) {
		String userId = region.getManager().getId();
		String regionId = region.getId();
		RegionUser regionUser = new RegionUser();
		regionUser.setRegionid(regionId);
		List<RegionUser> rus =  regionUserDao.findRegionUserByRegionId(regionUser);
		//一个区域有一个区域管理员
		if(rus!=null && rus.size()>0){
			RegionUser tempru = new RegionUser();
			tempru.setUserid(userId);
			tempru.setId(rus.get(0).getId());
			regionUserDao.updateRegionUserById(tempru);
		}else{
			regionUser.setUserid(userId);
			regionUser.preInsert();
			regionUserDao.insert(regionUser);
		}
		super.save(region);
	}
	
	@Transactional(readOnly = false)
	public void delete(Region region) {
		super.delete(region);
	}
	
}